package com.cy.hui_jie_dan.config;


import com.cy.hui_jie_dan.interceptor.JwtTokenUserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JwtTokenUserInterceptor authInterceptor;

    @Value("${file.upload-dir:./uploads}")
    private String uploadDir;

    @Value("${file.upload-dir.images:${user.dir}/src/main/resources/templates/img}")
    private String imageUploadDir;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080", "http://localhost:5173", "http://sa773a.natappfree.cc")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("Authorization", "Content-Type")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/api/**")  // Only handle /api/** paths
                .excludePathPatterns(
                    "/api/user/login",
                    "/api/user/register",
                    "/api/user/logout",
                    "/api/user/reset-password",
                    "/api/user/info",
                    "/api/friends/**",
                    "/api/chat/**",
                    "/ws/**",
                    "/img/**",
                    "/swagger-ui/**",
                    "/v3/api-docs/**",
                    "/swagger-resources/**"
                );
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 使用绝对路径配置图片访问
        String absolutePath = new File(imageUploadDir).getAbsolutePath();
        registry.addResourceHandler("/img/**")
                .addResourceLocations("file:" + absolutePath + File.separator)
                .setCachePeriod(3600)
                .resourceChain(true);
    }
}